package com.ttg.web.service.job.impl;

import com.google.common.util.concurrent.ListenableFuture;
import com.ttg.common.annotation.TaskRunMethod;
import com.ttg.common.enums.DimTypeEnum;
import com.ttg.common.enums.LadderRuleTypeEnum;
import com.ttg.common.enums.LivenessMctConfigEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.BigDecimalUtils;
import com.ttg.common.vo.TaskResultVO;
import com.ttg.model.dto.QualityManageReportDTO;
import com.ttg.common.dto.TaskBaseDTO;
import com.ttg.model.dto.job.IndustryScoreDTO;
import com.ttg.model.po.IndustryPO;
import com.ttg.model.pojo.*;
import com.ttg.model.vo.IndustryQualityVO;
import com.ttg.model.vo.IndustryTwoLevelVO;
import com.ttg.web.dao.*;
import com.ttg.web.juc.TasktemplateHelper;
import com.ttg.web.service.job.QualityManageCommon;
import com.ttg.web.service.job.IndustryScoreJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/8/27 17:47
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
@Service
@TaskRunMethod(value = "industryScoreTask")
public class IndustryScoreJobServiceImpl extends QualityManageCommon implements IndustryScoreJobService {

    @Value("${tlinx.isJuc:false}")
    private volatile Boolean isJuc;//是否启用异步回调
    @Autowired
    private TasktemplateHelper tasktemplateHelper;
    @Autowired
    private QualityManageIndustryReportDao industryReportDao;
    @Autowired
    private QualityManageLadderRuleDao ladderRuleDao;

    @Autowired
    private IndustryInfoDao industryInfoDao;
    @Autowired
    private ModelMctMonthDao modelMctMonthDao;
    @Autowired
    private LivenessMctConfigDao livenessMctConfigDao;

    /**
     * 行业活跃度，清算成本，户均归集，加权得分计算
     */
    @Override
    public TaskResultVO industryScore(TaskBaseDTO reqDto) {
        reqDto = getCheckYearAndMonth(reqDto);
        //根据行业质量评价规则(7类11阶),按月生成行业质量报告
        //1.查询所有二级行业分类
        List<IndustryTwoLevelVO> list = industryInfoDao.allTwoLevelList();

        List<QualityManageLadderRule> rules = ladderRuleDao.getByDimType(DimTypeEnum.行业维度.getValue());
        if(rules==null){
            throw new BaseException("行业阶梯评价规则不能为空");
        }
        List<ListenableFuture<TaskResultVO>> futures = new ArrayList<>();
        List<TaskResultVO> results = new ArrayList<>();
        for (IndustryTwoLevelVO industry:list){
            IndustryScoreDTO industryScoreDTO = new IndustryScoreDTO();
            industryScoreDTO.setIndustry(industry);
            industryScoreDTO.setLadderRules(rules);
            if(isJuc){
                futures.add(tasktemplateHelper.submit(this,reqDto,industryScoreDTO));
            }else {
                TaskResultVO result = industryScoreTask(reqDto,industryScoreDTO);
                results.add(result);
            }
        }
        return taskResult(results,futures,isJuc);
    }

    /**
     * 可异步处理的逻辑
     */
    public TaskResultVO industryScoreTask(TaskBaseDTO reqDto, IndustryScoreDTO industryScoreDTO){
        try {
            System.out.println(Thread.currentThread().getName());
            QualityManageIndustryReport report = new QualityManageIndustryReport();
            IndustryTwoLevelVO industryVO = industryScoreDTO.getIndustry();
            List<QualityManageLadderRule> rules = industryScoreDTO.getLadderRules();
            LivenessMctConfig livenessMctConfig = livenessMctConfigDao.getByType(LivenessMctConfigEnum.每月统计.getValue());
            IndustryQualityVO industryQualityVO = modelMctMonthDao.getIndustryQuality(reqDto.getYear(),reqDto.getMonth(),industryVO.getIndClsId2(),livenessMctConfig.getLmcDays());
            //行业活跃度得分
            industryLivenessScore(industryQualityVO, report, rules);
            //行业清算成本得分
            industryClearCostScore(industryQualityVO, report, rules);
            //行业户均归集得分
            industryAvgScore(industryQualityVO, report, rules);

            //加权得分
            QualityManageReportDTO reportDTO = new QualityManageReportDTO();
            BeanUtils.copyProperties(report, reportDTO);
            reportDTO = weightScore(reportDTO, DimTypeEnum.行业维度.getValue());
            report.setRepWeightScore(reportDTO.getRepWeightScore());

            report.setRepYear(reqDto.getYear());
            report.setRepMonth(reqDto.getMonth());
            report.setRepClsId1(industryVO.getIndClsId1());
            report.setRepClsId2(industryVO.getIndClsId2());
            report.setRepTotalMerchCount(industryQualityVO!=null?industryQualityVO.getTotalMctCount():0);
            report.setRepActiveMerchCount(industryQualityVO!=null?industryQualityVO.getLivenessMctCount():0);
            industryReportDao.saveOrUpd(report);
        }catch (BaseException e) {
            e.printStackTrace();
            return taskReuslt(Status.FAIL.getValue(),false, e.getMsg());
        }catch (Exception ex){
            ex.printStackTrace();
            String exType = ex.getClass().getSimpleName();
            return taskReuslt(Status.FAIL.getValue(),false,"异常类型：" + exType + ",异常信息：" + ex.getMessage());
        }
        return taskReuslt(Status.SUCCESS.getValue(),false,"ok");
    }

    /**
     * 行业活跃率得分
     * 行业活跃率 = 对应行业所选范围的活跃商户数/对应行业所选范围的总商户数
     */
    public void industryLivenessScore(IndustryQualityVO industry,QualityManageIndustryReport report,List<QualityManageLadderRule> rules){
        if(industry!=null) {
            //1. 计算行业活跃率
            BigDecimal rate = BigDecimalUtils.mul(BigDecimalUtils.div(industry.getLivenessMctCount(), industry.getTotalMctCount(), 4), 100);
            report.setRepLiveness(rate);
            //2. 匹配行业活跃率阶梯规则得分
            BigDecimal ruleScore = getRuleScore(LadderRuleTypeEnum.行业活跃度.getValue(), rate, rules);
            report.setRepLivenessScore(ruleScore);
        }
    }

    /**
     * 行业清算成本得分
     * 行业清算成本 = 对应行业所选范围商户的补贴额之和/对应行业所选范围商户的年日均存款的按户平均数
     */
    public void industryClearCostScore(IndustryQualityVO industry,QualityManageIndustryReport report,List<QualityManageLadderRule> rules){
        if(industry!=null) {
            //1. 计算行业清算成本
            //1.1 计算日均存款的按户平均数
            BigDecimal avgDepositAmt = BigDecimalUtils.div(industry.getAvgDepositAmt(), industry.getTotalMctCount(), 4);
            //1.2 计算行业清算成本
            BigDecimal clearCost = BigDecimalUtils.div(industry.getRepairAmt(), avgDepositAmt, 0);
            report.setRepClearCost(clearCost);
            //2. 匹配行业清算成本阶梯规则得分
            BigDecimal ruleScore = getRuleScore(LadderRuleTypeEnum.清算成本.getValue(), clearCost, rules);
            report.setRepClearCostScore(ruleScore);
        }
    }

    /**
     * 行业户均归集得分
     * 户均归集 = 对应行业所选范围商户的年日均存款的按户平均数
     */
    public void industryAvgScore(IndustryQualityVO industry,QualityManageIndustryReport report,List<QualityManageLadderRule> rules){
        if(industry!=null) {
            //1.1 计算日均存款的按户平均数
            BigDecimal avgDepositAmt = BigDecimalUtils.div(industry.getAvgDepositAmt(), industry.getTotalMctCount(), 0);
            report.setRepAvg(avgDepositAmt);
            //2. 匹配行业户均归集阶梯规则得分
            BigDecimal ruleScore = getRuleScore(LadderRuleTypeEnum.户均归集.getValue(), avgDepositAmt, rules);
            report.setRepAvgScore(ruleScore);
        }
    }

}
